#include "controller.h"
#include <iostream>
#include <sstream>
#include <thread>
#include <chrono>
#include <jsoncpp/json/json.h>
#include "http_client.h"
#include "api_server_client.h"
#include "pod_parser.h"
#include "task_parser.h"
#include "node_parser.h"
namespace nanok {

ControllerManager::ControllerManager(const std::string& api_server)
    : api_server_(api_server), running_(false) {
}

void ControllerManager::Start() {
    running_ = true;
    std::thread podControllerThread(&ControllerManager::podController, this);
    std::thread schedulerThread(&ControllerManager::scheduler, this);
    podControllerThread.detach();
    schedulerThread.detach();
    std::cout << "Controller manager started" << std::endl;
}

void ControllerManager::Stop() {
    running_ = false;
}

void ControllerManager::podController() {
    while (running_) {
        std::this_thread::sleep_for(std::chrono::seconds(5));
        try {
            std::vector<Pod> pods;
            nanok::getPods(pods);
            for (const auto& pod : pods) {
                if (pod.status.phase == "Pending") {
                    // 创建 Task
                    Task task;
                    task.metadata.name = "task-" + pod.metadata.name;
                    task.metadata.resourceVersion = 1;
                    task.spec.podName = pod.metadata.name;
                    std::string key = "/tasks/" + task.metadata.name;
                    std::string value = to_json(task);
                    nanok::submitTask(key, value);
                }
            }
        } catch (const std::exception& e) {
            std::cerr << "Error in pod controller: " << e.what() << std::endl;
        }
    }
}

void ControllerManager::scheduler() {
    while (running_) {
        std::this_thread::sleep_for(std::chrono::seconds(5));
        try {
            std::vector<Node> nodes;
            std::vector<Task> tasks;
            nanok::getTasks(tasks);
            for (auto& task : tasks) {
                if (task.spec.assignedNode.empty()) {
                    // 简单调度策略：选择第一个节点
                    Node node;
                    nanok::getNodes(nodes);
                    if (nodes.size() > 0) {
                        task.spec.assignedNode = nodes[0].metadata.name;
                        task.metadata.resourceVersion++;
                        std::string key = "/tasks/" + task.metadata.name;
                        std::string value = to_json(task);
                        nanok::updateTask(key, value);
                    } else {
                        std::cout << "没有足够的节点来运行该任务！" << std::endl;
                    }
                }
            }
        } catch (const std::exception& e) {
            std::cerr << "Error in scheduler: " << e.what() << std::endl;
        }
    }
}

} // namespace nano_k8s